<template>
  <div class="table-catalog">
    <div class="table-catalog-title">
      <span style="cursor: pointer" @click="handleChangeCatalog">{{ props.title }}</span>
      <el-button v-permission="'user:tag:add'" text link @click="openFormCatalog({}, null)">
        <el-icon>
          <CirclePlus />
        </el-icon>
      </el-button>
    </div>
    <el-tree
      ref="treeRef"
      :data="treeData"
      :props="{ value: 'id', label: 'tagName', children: 'childrenList' }"
      :expand-on-click-node="false"
      :current-node-key="currentNodeKey"
      highlight-current
      node-key="id"
      draggable
      @node-drop="handleDrop"
      @node-click="handleChangeCatalog"
    >
      <template #default="{ data }">
        <span class="table-catalog-item">
          <img src="@/assets/images/label.svg" />
          <span class="table-catalog-name">{{ data.tagName }}</span>
          <span class="table-catalog-dropdown">
            <el-dropdown style="margin-top: 3px">
              <el-icon><More /></el-icon>
              <template #dropdown>
                <el-dropdown-menu>
                  <div v-permission="'user:tag:edit'" @click="openFormCatalog(data, null)">
                    <el-dropdown-item>修改</el-dropdown-item>
                  </div>
                  <div v-permission="'user:tag:delete'" @click="deleteCatalog(data)">
                    <el-dropdown-item>删除</el-dropdown-item>
                  </div>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </span>
        </span>
      </template>
    </el-tree>
  </div>
  <catalog-form ref="catalogRef" @refresh="handleCatalog" />
</template>

<script setup>
  import { computed, nextTick, onMounted, ref } from 'vue'
  import { commonApi } from '@/api/common'
  import CatalogForm from './TagForm.vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { useTagStore } from '@/store/modules/tag.js'

  const tagStore = useTagStore()

  const emit = defineEmits(['update:tag-id', 'refresh'])

  const props = defineProps({
    title: {
      type: String,
      default: '标签'
    },
    tagType: {
      type: Number,
      default: 0
    },
    tagId: {
      type: String,
      default: ''
    },
    firstDefault: {
      // 默认选中第一个
      type: Boolean,
      default: true
    }
  })

  const tagId = computed(() => {
    return props.tagId
  })
  const tagType = computed(() => {
    return props.tagType
  })
  const currentNodeKey = ref('')

  const treeRef = ref()

  // 选择目录
  const handleChangeCatalog = (item) => {
    currentNodeKey.value = item.id
    emit('update:tag-id', item.id)
    emit('refresh')
  }

  const handleDrop = (node, before) => {
    commonApi
      .tagSort([
        { id: node.data.id, sort: before.data.sort },
        { id: before.data.id, sort: node.data.sort }
      ])
      .then((res) => {
        ElMessage.success(res)
        handleCatalog()
      })
  }

  // 删除
  const deleteCatalog = (item) => {
    ElMessageBox.confirm('删除标签后，该标签下的所有用户将失去该标签属性。确定删除吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      commonApi.tagDelete(item).then((res) => {
        ElMessage.success(res)
        handleCatalog()
      })
    })
  }

  // 添加/修改文件夹
  const catalogRef = ref()
  const openFormCatalog = (item, parentId) => {
    item.tagType = tagType.value
    catalogRef.value.onOpen(item, parentId)
  }

  // 列出文件夹
  const treeData = ref()
  const firstTree = ref()
  onMounted(() => {
    if (tagId.value) {
      treeRef['value'].setCurrentKey(tagId.value)
    }
    handleCatalog()
  })

  // 列出目录
  const handleCatalog = () => {
    commonApi.tagList({ tagType: props.tagType }).then((res) => {
      if (res) {
        tagStore.init(res)

        treeData.value = res
        firstTree.value = res[0]

        if (props.firstDefault) {
          nextTick(() => {
            handleChangeCatalog(res[0])
          })
        }
      }
    })
  }
</script>
<style lang="scss" scoped>
  .table-catalog {
    display: block;
    width: 200px;
    overflow: auto;
    border: 1px solid #ebeef5;

    .table-catalog-title {
      cursor: default;
      padding: 10px 20px;
      display: flex;
      justify-content: space-between;
    }

    .table-catalog-item {
      display: flex;
      align-items: center;
    }

    .table-catalog-name {
      position: relative;
      margin-left: 5px;
      overflow: hidden;
    }

    .table-catalog-dropdown {
      display: none;
      right: 0;
      position: absolute;
      margin: 0 auto;
      padding: 0 10px;
    }
  }

  .el-tree-node__content:hover {
    .table-catalog-dropdown {
      display: block;
    }
  }
</style>
